In [2]:
%pylab inline
In [3]:
import sys
from time import time
import matplotlib as pl
import matplotlib.pyplot as plt
import pickle
In [4]:
dataPath = '/Users/omojumiller/mycode/MachineLearningNanoDegree/IntroToMachineLearning/'
sys.path.append(dataPath+'tools/')
sys.path.append(dataPath+'final_project/')
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
In [5]:
### Load the dictionary containing the dataset
with open(dataPath+'final_project/final_project_dataset.pkl', "r") as data_file:
data_dict = pickle.load(data_file)
In [7]:
# Remove the source of the outlier
data_dict.pop( 'TOTAL')
Out[7]:
In [20]:
features_list = [ 'long_term_incentive', 'bonus']
data = featureFormat(data_dict, features_list, remove_any_zeroes=True)
for point in data:
salary = point[0]
bonus = point[1]
plt.scatter( salary, bonus )
#plt.xticks(np.arange(0, 1e6, 200000), rotation = -60)
plt.xlim((0, 1e7))
plt.xlabel("bonus")
plt.ylabel("long_term_incentive")
plt.show()
In [21]:
def doPCA():
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(data)
return pca
In [22]:
pca = doPCA()
In [23]:
print pca.explained_variance_ratio_
In [27]:
first_pc = pca.components_[0]
second_pc = pca.components_[1]
print first_pc, second_pc
In [25]:
transformed_data = pca.transform(data)
In [30]:
for ii, jj in zip(transformed_data, data):
plt.scatter( first_pc[0]*ii[0], first_pc[1]*ii[0], color='r' )
plt.scatter( second_pc[0]*ii[1], second_pc[1]*ii[1], color='c' )
plt.scatter(jj[0], jj[1], color='b') #original data
#plt.xlim((0, 1e7))
plt.xlabel("bonus")
plt.ylabel("long_term_incentive")
plt.show()
In [31]:
print __doc__
from time import time
import logging
import pylab as pl
import numpy as np
In [32]:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC
In [33]:
# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
In [34]:
# Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
In [35]:
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape
np.random.seed(42)
In [36]:
# for machine learning we use the data directly (as relative pixel
# position info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]
# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]
print "Total dataset size:"
print "n_samples: %d" % n_samples
print "n_features: %d" % n_features
print "n_classes: %d" % n_classes
In [37]:
# Split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
In [48]:
def computeEigenfaces():
print "Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0])
t0 = time()
pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train)
print "done in %0.3fs" % (time() - t0)
eigenfaces = pca.components_.reshape((n_components, h, w))
print "Projecting the input data on the eigenfaces orthonormal basis"
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print "done in %0.3fs" % (time() - t0)
# Train a SVM classification model
print "Fitting the classifier to the training set"
t0 = time()
param_grid = {
'C': [1e3, 5e3, 1e4, 5e4, 1e5],
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1],
}
# for sklearn version 0.16 or prior, the class_weight parameter value is 'auto'
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print "done in %0.3fs" % (time() - t0)
print "Best estimator found by grid search:"
print clf.best_estimator_
# Quantitative evaluation of the model quality on the test set
print "Predicting the people names on the testing set"
t0 = time()
y_pred = clf.predict(X_test_pca)
print "done in %0.3fs" % (time() - t0)
print classification_report(y_test, y_pred, target_names=target_names)
print confusion_matrix(y_test, y_pred, labels=range(n_classes))
In [42]:
# Qualitative evaluation of the predictions using matplotlib
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
"""Helper function to plot a gallery of portraits"""
pl.figure(figsize=(1.8 * n_col, 2.4 * n_row))
pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
for i in range(n_row * n_col):
pl.subplot(n_row, n_col, i + 1)
pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray)
pl.title(titles[i], size=12)
pl.xticks(())
pl.yticks(())
# plot the result of the prediction on a portion of the test set
def title(y_pred, y_test, target_names, i):
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
In [53]:
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
for i in [10, 15, 25, 50, 100, 250]:
print '\n', '-' * 45, '\n'
print "Computing eigenfaces with ", i, " principal components"
print '\n', '-' * 45
n_components = i
computeEigenfaces()
In [43]:
prediction_titles = [title(y_pred, y_test, target_names, i)
for i in range(y_pred.shape[0])]
plot_gallery(X_test, prediction_titles, h, w)
In [44]:
# plot the gallery of the most significative eigenfaces
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
pl.show()
In [45]:
pca.explained_variance_ratio_
Out[45]:
In [ ]: